package com.dc.free.util;

import java.util.Set;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;

public class ControllerUtil {

	/**
	 * 定义返回数据格式
	 * @param c
	 * @param code
	 * @param msg
	 * @param stack
	 * @param data
	 * @return
	 */
	public static StatusUtil renderStatus(Controller c, String code, String msg, String stack, Object data, Object... args) {
		StatusUtil su = StatusUtil.create();
		c.renderJson(su.getStatus(code, msg, stack, data));
		
		return su;
	}
	
	public static StatusUtil renderOk(Controller c, String msg, Object data, Object... args) {
		return renderStatus(c, "0", msg, null, data, args);
	}
	
	public static StatusUtil renderOk(Controller c, Object data) {
		return renderStatus(c, "0", null, null, data);
	}
	
	public static StatusUtil renderOk(Controller c, String msg, Object... args) {
		return renderStatus(c, "0", msg, null, null, args);
	}
	
	public static StatusUtil renderOk(Controller c) {
		return renderStatus(c, "0", null, null, null);
	}
	
	public static StatusUtil renderError(Controller c, String code, String stack, Object data, Object... args) {
		return renderStatus(c, code, null, stack, data, args);
	}
	
	public static StatusUtil renderError(Controller c, String code, String stack, Object... args) {
		return renderStatus(c, code, null, stack, null, args);
	}
	
	public static StatusUtil renderError(Controller c, String code, Object data, Object... args) {
		return renderStatus(c, code, null, null, data, args);
	}
	
	public static StatusUtil renderError(Controller c, String code, Object... args) {
		return renderStatus(c, code, null, null, null, args);
	}
	
	public static StatusUtil renderError(Controller c) {
		return renderStatus(c, "1", null, null, null);
	}
	
	/**
	 * 获取参数json
	 */
	public static JSONObject getParameters(Controller c) {
		JSONObject json = new JSONObject();
		Set<Entry<String, String[]>> paras = c.getParaMap().entrySet();
		for (Entry<String, String[]> para : paras) {
			json.put(
					para.getKey(),
					para.getValue().length > 1 ? para.getValue() : para.getValue()[0]);
		}
		return json;
	}
	
	/**
	 * 获取参数名json
	 * @param c
	 * @return
	 */
	public static JSONObject getParameterName(Controller c) {
		String paraName = c.getParaNames().nextElement();
		return JSON.parseObject(paraName);
	}
	
}
